<?php

namespace App\Admin\Service\Base;


use App\Admin\Service\AbstractAdminService;
use App\Admin\Service\Traits\DestroyServiceTrait;
use App\Admin\Service\Traits\StoreServiceTrait;
use App\Admin\Service\Traits\SwitchServiceTrait;
use App\Admin\Service\Traits\UpdateServiceTrait;
use App\Common\Enums\Base\SuperConfigEnumType;
use App\Common\Exception\ApiMessageException;
use App\Common\Model\Base\SuperConfig;
use App\Common\Util\EasySearch;
use App\Common\Util\TP;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

/**
 * Class SuperConfigService
 */
class SuperConfigService extends AbstractAdminService
{
    use StoreServiceTrait, UpdateServiceTrait, DestroyServiceTrait, SwitchServiceTrait;

    public function __construct()
    {
        $this->model = new SuperConfig();
    }

    /**
     * @return array
     */
    public function lists(): array
    {
        $query = $this->model->alias('super_config')
            ->order('id', 'asc')
            ->field(["super_config.id","super_config.sign","super_config.name","super_config.type","super_config.create_time"]);

        return EasySearch::create($query)->getData();
    }

    public function beforeWrite(&$data, $id = null): void
    {
        if ($data['type'] === SuperConfigEnumType::AdvancedArray->value) {
            foreach ($data['config_info'] ?? [] as $info) {
                if ($info['formType'] == 'editor') {
                    throw new ApiMessageException('高级数组类型不支持富文本');
                }
            }
        }
    }

    /**
     * 保存配置信息
     *
     * @param array $data
     *
     * @return void
     * @throws ApiMessageException
     */
    public function saveBase(array $data): void
    {
        if (empty($data['id'])) {
            throw new ApiMessageException("无法保存");
        }

        $superConfig = SuperConfig::find($data['id']);

        unset($data['id']);

        if ($superConfig->type === SuperConfigEnumType::AdvancedArray->value) {
            $superConfig->config_value = $superConfig->config_value ?: [];
            if (empty($data['cid'])) {
                $data['cid'] = $superConfig->config_value ? max(array_column($superConfig->config_value, 'cid')) + 1 : 1;
                $superConfig->config_value = [...$superConfig->config_value, $data];
            }else{
                $superConfig->config_value = array_map(function ($value) use ($data){
                    return $value['cid'] === $data['cid'] ? $data : $value;
                }, $superConfig->config_value);
            }
        }else{
            $superConfig->config_value = $data;
        }
        $superConfig->save();
    }

    /**
     * @param int $id
     * @param array $deleteIds
     *
     * @return void
     * @throws ApiMessageException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function advancedArrayDataDestroy(int $id, array $deleteIds): void
    {
        $superConfig = SuperConfig::find($id);
        if (!$superConfig) {
            throw new ApiMessageException('信息错误');
        }

        $newData = array_filter($superConfig->config_value, function ($value) use ($deleteIds){
            return !in_array($value['cid'], $deleteIds);
        });

        $superConfig->config_value = array_values($newData);
        $superConfig->save();
    }


    public static function supportForm(): array
    {
        return [
            ['label' => '隐藏域', 'value' => 'hidden'],
            ['label' => '文本', 'value' => 'text'],
            ['label' => '日期时间', 'value' => 'datetime'],
            ['label' => '图片', 'value' => 'image'],
            ['label' => '图片（多）', 'value' => 'images'],
            ['label' => '开关', 'value' => 'switch'],
            ['label' => '单选', 'value' => 'radio'],
            ['label' => '多选', 'value' => 'checkbox'],
            ['label' => '下拉', 'value' => 'select'],
            ['label' => '下拉（多）', 'value' => 'selects'],
            ['label' => '文本域', 'value' => 'textarea'],
            ['label' => '富文本', 'value' => 'editor'],
            ['label' => '上传', 'value' => 'upload'],
        ];
    }


    /**
     * @param int $page
     * @param int $limit
     *
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function advancedArrayData(int $page, int $limit): array
    {
        /** @var SuperConfig $superConfig */
        $superConfig = $this->model->find(EasySearch::query('id'));
        $allData =\App\Common\Service\SuperConfigService::get($superConfig->sign, latest: true);

        foreach ($allData as &$datum) {
            $newData = [];
            foreach ($datum as $field => $item) {
                $newData[$field] = $item;
                if (!is_array($item)) {
                    continue;
                }
                if (count($item) == count($item, COUNT_RECURSIVE)) {
                    $newData[$field]         = $item['value'] ?? null;
                    $newData["{$field}_des"] = $item['label'] ?? null;
                } else {
                    if (isset($item[0]['value']) && isset($item[0]['label'])) {
                        $newData[$field]         = array_column($item, 'value');
                        $newData["{$field}_des"] = implode(',', array_column($item, 'label'));
                    }
                }
            }
            $datum = $newData;
        }
        unset($datum);

        if ($search = TP::request()->get('search')) {
            $searchValue = array_filter(empty($search['search']) ? [] : $search['search']);
            foreach ($searchValue as $field => $sv) {
                $allData = array_filter($allData, fn($value) => str_contains($value[$field] ?? "", $sv));
            }
        }

        $data = array_slice($allData, ($page - 1) * $limit, $limit);

        return [
            'data'  => $data,
            'total' => count($allData),
        ];
    }
}
